import { Command } from 'commander';
import colors from 'colors';
import axios, { AxiosResponse } from 'axios';
import { IWeatherResponse } from './indexDTO'

const URL = 'http://apis.juhe.cn/simpleWeather/query';  // 聚合数据 API
const KEY = '[你的key值]'; // 聚合数据 API 的 Key 
const log = console.log;
const program = new Command();

const command = program
    .option('-c, --city [name]', 'Type City Name')
    .parse(process.argv);
const opts = command.opts();
if (!opts.city) {
    command.outputHelp();
}
if (process.argv.slice(-2).length === 0) {
    command.outputHelp(colors.red);
    process.exit();
}

log(colors.bgYellow.red('用户输入：'));
log(colors.bgYellow.red(opts as unknown as string));

const getWeather = async (city: string) => {
    try {
        const url = `${URL}?city=${encodeURI(city)}&key=${KEY}`;
        const res = await axios.get(url) as AxiosResponse<IWeatherResponse>;
        const result = res.data.result;
        log(colors.bgCyan.yellow('————————————————————————'));
        log(colors.bgCyan.yellow(' 今天 '));
        log(colors.bgCyan.yellow(` 天气：${result.realtime.info} `));
        log(colors.bgCyan.yellow(` 温度：${result.realtime.temperature} ℃ `));
        log(colors.bgCyan.yellow(` 指数：${result.realtime.aqi} `));
        log(colors.bgCyan.yellow(` 风力：${result.realtime.direct} ${result.realtime.power} `));
        result.future.forEach((item, index) => {
            log(colors.bgCyan.yellow('————————————————————————'));
            log(colors.bgCyan.yellow(` ${index === 0 ? '明天' : index === 1 ? '后天' : item.date} `));
            log(colors.bgCyan.yellow(` 天气：${item.weather} `));
            log(colors.bgCyan.yellow(` 温度：${item.temperature} `));
            log(colors.bgCyan.yellow(` 风力：${item.direct} ${result.realtime.power} `));
        })
        log(colors.bgCyan.yellow('————————————————————————'));
    } catch {
        log(colors.red('天气服务出现异常❗️❗️❗️'));
    }
}

void getWeather(opts.city);
